import axios from "axios";
import { defineStore } from "pinia";
import { ElMessage } from "element-plus";
import { ref } from 'vue'
import { useRouter } from "vue-router";
export const useUserStore = defineStore('user', () => {
  const router = useRouter()
  const isLogin = ref(null)
  const isReg = ref(null)
  //用户注册
  const regUser = async (user) => {
    const { data } = await axios.get('http://localhost:3000/userList')
    const flag = data.find(item => item.username == user.username)
    if (flag) {
      ElMessage.error('用户名被占用');
      isReg.value = false
    } else {
      await axios.post('http://localhost:3000/userList', user)
      ElMessage.success('注册成功');
      isReg.value = true
    }
  }

  //用户登入
  const loginUser = async (user) => {
    const { data } = await axios.get('http://localhost:3000/userList')
    const Uname = data.find(item => item.username == user.username)
    const flag = data.find(item => item.username == user.username && item.password == user.password)
    // console.log(flag)
    if (flag) {
      if(flag.id=='root'){
        ElMessage.success('进入管理');
      }else{
        ElMessage.success('登入成功');
      }
      
      localStorage.setItem('userId', flag.id)
    } else {
      if (Uname) {
        ElMessage.error('账号或密码错误');
      } else {
        ElMessage.error('没有该用户');
      }
    }
  }
  return {
    regUser, isLogin, loginUser, isReg
  }
})